package com.lovo.service.impl;

import com.lovo.dao.InvoiceDAO;
import com.lovo.model.InvoiceDO;
import com.lovo.service.InvoiceService;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

@Service
public class InvoiceServiceImpl implements InvoiceService {
    @Resource
    private InvoiceDAO invoiceDAO;
    @Override
    public List findByDynamic(String type, String value) {
        return invoiceDAO.findAll(new Specification<InvoiceDO>() {
            @Override
            public Predicate toPredicate(Root<InvoiceDO> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicateList = new ArrayList();
                predicateList.add(criteriaBuilder.equal(root.get(type),value));
                predicateList.add(criteriaBuilder.like(root.get("url"),"%lovo%"));
                return criteriaBuilder.and(predicateList.toArray(new Predicate[predicateList.size()]));
            }
        });
    }

    @Override
    public List findAll() {
        return invoiceDAO.findAll();
    }

    @Override
    public void save(InvoiceDO invoiceDO) {
        invoiceDAO.save(invoiceDO);
    }

    @Override
    public void delete(InvoiceDO invoiceDO) {
        invoiceDAO.delete(invoiceDO);
    }
}
